﻿using System;
using System.ComponentModel.Composition;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.SharePoint;
using Microsoft.VisualStudio.Shell;

namespace CodeCounsel.SharePoint.RibbonDesigner
{
    [Export(typeof(ISharePointProjectItemTypeProvider)),
    SharePointProjectItemType("CodeCounsel.SharePoint.RibbonDesigner.Ribbon")]
    public class RibbonItemTypeProvider
        : ISharePointProjectItemTypeProvider
    {
        ISharePointProjectService _projectService;

        public void InitializeType(
            ISharePointProjectItemTypeDefinition typeDefinition)
        {
            _projectService = typeDefinition.ProjectService;
            typeDefinition.SupportedAssemblyDeploymentTargets = 
                SupportedAssemblyDeploymentTargets.All;
            typeDefinition.SupportedDeploymentScopes =
                SupportedDeploymentScopes.Site |
                SupportedDeploymentScopes.Web;
            typeDefinition.SupportedTrustLevels = 
                SupportedTrustLevels.All;
            typeDefinition.ProjectItemMenuItemsRequested += 
                TypeDefinition_ProjectItemMenuItemsRequested;
        }

        void TypeDefinition_ProjectItemMenuItemsRequested(
            object sender, SharePointProjectItemMenuItemsRequestedEventArgs e)
        {
            IMenuItem viewDesignerAction = e.ViewMenuItems.Add("View Ribbon Designer");
            viewDesignerAction.Click += delegate
            {
                try
                {
                    VsShellUtilities.OpenDocumentWithSpecificEditor(
                        _projectService.ServiceProvider,
                        LocateRibbonDefinitionFile(e.ProjectItem).FullPath,
                        GuidList.EditorFactory,
                        VSConstants.LOGVIEWID.Designer_guid);
                }
                catch (COMException) { }
            };
        }

        ISharePointProjectItemFile LocateRibbonDefinitionFile(
            ISharePointProjectItem projectItem)
        {
            ISharePointProjectItemFile file = projectItem.DefaultFile;
            if (file == null)
            {
                file = projectItem.Files["Elements.xml"];
            }
            return file;
        }
    }
}
